package windows
{
	import com.bit101.components.Window;
	import flash.display.ActionScriptVersion;
	import windows.SketchHolder;
	import flash.display.Sprite;
	import windows.DraggableWindow;
	import flash.events.MouseEvent;
	import baseitems.Item;
	import property.ItemType;
	import baseitems.Base;
	import property.Align;
	
	/**
	 * поле на котором мы все расставляем
	 * тутачки и происходит расстановка всех и вся
	 * @author yaempechenki@gmail.com
	 */
	public class FormWindow extends Window //DraggableWindow
	{
		private var grid:Sprite;
		private var container:Sprite;
        private var sketchHolder:SketchHolder;
		
		public function FormWindow()
		{
			title = "Form";
			hasMinimizeButton = true;
			
			sketchHolder = new SketchHolder();
			//sketchHolder.mouseEnabled = false;
			addChild(sketchHolder);
			
			grid = new Sprite();
			//grid.mouseEnabled = false;
			grid.x = grid.y = 1;
			addChild(grid);
			
			container = new Sprite();
			container.x = container.y = 1;
			addChild(container);
			
			container.addEventListener(MouseEvent.CLICK, onClick);
			grid.addEventListener(MouseEvent.CLICK, onFormClick);
		}
		
		private function onFormClick(event:MouseEvent):void {
			Controller.instance.selectedObject = null;
		}
		
		private function onClick(event:MouseEvent):void {
			if (event.target.parent is Item) {
				Controller.instance.selectedObject = event.target.parent as Item;
			} 
		}

		public function addSketch():void {
			sketchHolder.openFile();
		}
		
		public function setFormSize(formWidth:int, formHeight:int):void {
			width = formWidth;
			height = formHeight + 20;
			
			grid.graphics.clear();
			grid.graphics.lineStyle(1, 0xAAAAAA);
			grid.graphics.beginFill(0xFFFFFF, 0.1);
			grid.graphics.drawRect(0, 0, formWidth, formHeight); 
			grid.graphics.endFill() ;
			const STEP_SIZE:int = 10;
			var count:int = Math.max(formWidth, formHeight)/STEP_SIZE;
			for (var i:int = 0; i < count; i++) 
			{
				var step:int = STEP_SIZE * i;
				grid.graphics.moveTo(0, step);
				grid.graphics.lineTo(formWidth,  step );

				grid.graphics.moveTo(step, 0);
				grid.graphics.lineTo(step, formHeight );
			}
			
			sketchHolder.setSize(formWidth, formHeight);
		}

		public function refresh():void {
			while (container.numChildren > 0) {
				container.removeChildAt(0);
			}
			
			var levelList:Object = Controller.instance.getLevelsList();
			for each (var list:Object in levelList) {
				for (var i:int = 0; i < list.length ; i++) 
				{
					var child:Base = Controller.instance.getItemById(list[i]);
					container.addChild(child);
				}
			}
            // просто затыка
            if(Controller.instance.getItems().length==0) return;
			arrange();
			// выделенный - наверх
			if (Controller.instance.selectedObject) {
				container.addChild(Controller.instance.selectedObject);
			}
		}
		
		public function arrange():void {
			const gridWidth:int = width;
			const gridHeight:int = height-20;
			
			var rootX:int = 0;
			var rootY:int = 0;
			var rootWidth:int = 0;
			var rootHeight:int = 0;
			var child:Base;
			var levelList:Object = Controller.instance.getLevelsList();
			for each (var list:Object in Controller.instance.getLevelsList()) {
				for each (var level:int in list) {
					child = Controller.instance.getItemById(level);
					const haveParent:Boolean = (child.selfParent != null);
					// auto size;
					if (haveParent) {
						if (child.percentWidthEnabled) {
							var pWidth:int = child.selfParent.width;
							child.width = pWidth / 100 * child.percentWidth;
						}
						if (child.percentHeightEnabled) {
							var pHeight:int = child.selfParent.height;
							child.height = pHeight / 100 * child.percentHeight;
						}
					} else {
						if (child.percentWidthEnabled) child.width = gridWidth / 100 * child.percentWidth;
						if (child.percentHeightEnabled) child.height = gridHeight / 100 * child.percentHeight;
					}
					// align-anchor
					if (haveParent) {
						rootX = child.selfParent.x + child.selfParent.container.x+1;
						rootY = child.selfParent.y + child.selfParent.container.y+1;//не могу объяснить эту еденицу
						rootWidth = child.selfParent.width;
						rootHeight = child.selfParent.height;
						if (child.selfParent.type == ItemType.LAYER) continue;
					} else {
						rootX = 0;
						rootY = 0;
						rootWidth = gridWidth;
						rootHeight = gridHeight;
					}
					
					// padding
					//rootX += child.padding.left;
					//rootY += child.padding.up;
					//rootWidth += child.padding.right;
					//rootHeight += child.padding.down;
					
					
					if (child.posAlign == Align.TOP_LEFT) child.setPosition(rootX, rootY);
					if (child.posAlign == Align.MIDDLE_LEFT) child.setPosition(rootX, rootY + rootHeight/2);
					if (child.posAlign == Align.BOTTOM_LEFT) child.setPosition(rootX, rootY + rootHeight);
					
					if (child.posAlign == Align.MIDDLE_TOP) child.setPosition(rootX+rootWidth/2, rootY);
					if (child.posAlign == Align.MIDDLE) child.setPosition(rootX+rootWidth/2, rootY+rootHeight/2);
					if (child.posAlign == Align.MIDDLE_BOTTOM) child.setPosition(rootX+rootWidth / 2, rootY+rootHeight);
					
					if (child.posAlign == Align.TOP_RIGHT) child.setPosition(rootX+rootWidth, rootY);
					if (child.posAlign == Align.MIDDLE_RIGHT) child.setPosition(rootX+rootWidth, rootY + rootHeight/2);
					if (child.posAlign == Align.BOTTOM_RIGHT) child.setPosition(rootX + rootWidth, rootY + rootHeight);
					child.refresh();
				}
			}
			//auto align
			var parents:Array = Controller.instance.getParentList();
			for (var i:int = 0; i < parents.length; i++) {
				var parent:Base = Controller.instance.getItemById(parents[i]);
				if (!parent) continue;
				if (parent.type != ItemType.LAYER) continue;
				
				rootX = parent.x + parent.container.x;
				rootY = parent.y + parent.container.y;
				rootWidth = parent.width;
				rootHeight = parent.height;
				
				var xPos:int = rootX;
				var yPos:int = rootY;
				var stackWidth:int = 0;
				var stackHeight:int = 0;
				// todo: заменить на "палучить суммарную ширину/высоту всех патомкав
				// заебашить уже специальный объект {потомок дети общая ширина общая высота уровень вложения в дереве}
				for each (child in Controller.instance.getItemsByParentId(parent.id)) {
					child.x = xPos;
					child.y = yPos;

					if (parent.wstack) {
						xPos += child.width;
						stackWidth += child.width;
						stackHeight = Math.max(child.height,stackHeight);
					}
					if (parent.hstack) {
						yPos += child.height;
						stackHeight += child.height;
						stackWidth = Math.max(child.width,stackWidth);
					}
				}

				// потомки располагаются внутри размеров предка
				for each (child in Controller.instance.getItemsByParentId(parent.id)) {
					child.anchor = parent.stackAlign;
					if (parent.hstack) {
						if (parent.stackAlign == Align.TOP_LEFT) {
							child.anchor = parent.stackAlign
						}
						if (parent.stackAlign == Align.MIDDLE_LEFT) {
							child.y += parent.height / 2 - stackHeight / 2 + child.height / 2;
						}
						if (parent.stackAlign == Align.BOTTOM_LEFT) {
							child.y += parent.height - stackHeight +  child.height;
						}
						if (parent.stackAlign == Align.MIDDLE_TOP) {
							child.x = rootX + parent.width / 2;
						}
						if (parent.stackAlign == Align.MIDDLE) {
							child.x = rootX + parent.width / 2;
							child.y += parent.height / 2 - stackHeight / 2 + child.height / 2;
						}
						if (parent.stackAlign == Align.MIDDLE_BOTTOM) {
							child.x = rootX + parent.width / 2;
							child.y += parent.height - stackHeight  + child.height;
						}
						if (parent.stackAlign == Align.TOP_RIGHT) {
							child.x = rootX + parent.width;
						}
						if (parent.stackAlign == Align.MIDDLE_RIGHT) {
							child.x = rootX + parent.width;
							child.y += parent.height / 2 - stackHeight / 2 + child.height / 2;
						}
						if (parent.stackAlign == Align.BOTTOM_RIGHT) {
							child.x = rootX + parent.width;
							child.y += parent.height - stackHeight + child.height;
						}
					}
					
					if(parent.wstack) {
						if (parent.stackAlign == Align.TOP_LEFT) {
							child.anchor = parent.stackAlign
						}
						if (parent.stackAlign == Align.MIDDLE_LEFT) {
							child.y = rootY + parent.height/2;
						}
						if (parent.stackAlign == Align.BOTTOM_LEFT) {
							child.y = rootY + parent.height;
						}
						if (parent.stackAlign == Align.MIDDLE_TOP) {
							child.x += parent.width/2 - stackWidth/2 + child.width/2;
						}
						if (parent.stackAlign == Align.MIDDLE) {
							child.x += parent.width/2 - stackWidth/2 + child.width/2;
							child.y = rootY + parent.height/2;
						}
						if (parent.stackAlign == Align.MIDDLE_BOTTOM) {
							child.x += parent.width/2 - stackWidth/2 + child.width/2;
							child.y = rootY + parent.height;
						}
						if (parent.stackAlign == Align.TOP_RIGHT) {
							child.x += parent.width - stackWidth + child.width;
						}
						if (parent.stackAlign == Align.MIDDLE_RIGHT) {
							child.x += parent.width - stackWidth + child.width;
							child.y = rootY + parent.height/2;
						}
						if (parent.stackAlign == Align.BOTTOM_RIGHT) {
							child.x += parent.width - stackWidth + child.width;
							child.y = rootY + parent.height;
						}
					}
					child.refresh();
				}
				if (parent.copySize) {
					// размер предка = суммарным размерам потомков
					parent.width = stackWidth;
					parent.height = stackHeight;
				}
				
			}
		}
    }
}